package increment1;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.TreeMap;

/**
 * PeopleView class is a singleton representing the people view in the TMS
 * 
 * @author Amer Alhalabi/Rolf Schmidt
 * @version 1.0
 *
 */
public class PeopleView {	
	
	///  the only instance of the class 
	private static PeopleView s_instance = null;
	
	/// holds all people objects
	private TreeMap<String, Person> personList;  
	
	/**
	 * getInstance is a function that returns the only instance
	 * of the class
	 * 
	 * @return PeopleView only instance
	 */
	public static PeopleView getInstance() {
		if (s_instance == null) {
			s_instance = new PeopleView();
		}
		return s_instance;
	}
	
	/**
	 * default constructor
	 * note: it is private to prevent creating multiple instances
	 */
	private PeopleView() {
		personList =  new TreeMap<String, Person>();
	}
	
	/**
	 * a getter of people and their tasks
	 * 
	 * @return a map of person Name to its Person object
	 */
	public TreeMap<String, Person> getPersonList() {
		return personList;
	}
	
	/**
	 * save the people view to a file
	 * 
	 * @param fileName path to the file where the content of the 
	 * people view is saved
	 */
	public boolean saveFile(String fileName) {

		PrintWriter printOut = null; // to save personList to a text file

		try {
			printOut = new PrintWriter(fileName); // generate output text file
			for (Map.Entry<String, Person> entry : personList.entrySet()) {
				printOut.print(entry.getValue().toString()); // add Person to
																// text file
			}
			printOut.close();
			return true;
		}
		catch (FileNotFoundException e) {
			System.out.println("File not found");
			System.out.println(e.getMessage());
			return false;
		}
		catch (NullPointerException e) {
			System.out.println("Filename is null");
			System.out.println(e.getMessage());
			return false;
		}
	}
	
	public void printPersonList() {
		final String H_LINE = "***************************************"; 
		
		System.out.println(H_LINE);
		System.out.println("People");
		System.out.println(H_LINE);
		
		for (Map.Entry<String, Person> entry : personList.entrySet()) {
			System.out.println(entry.getValue().toString()); 
		}
	}
}
